extends Area2D

# 设置速度大小
@export var speed = 600

# 小球速度的方向
var direction: Vector2 = Vector2.ZERO

# 小球初始位置
var initial_position: Vector2

# 屏幕大小
var screen_size

# 设置小球从屏幕下边缘滑出的信号，表示失败
signal leaved

# 小球和滑板发生碰撞
signal hit

func _ready() -> void:
	direction = Vector2.DOWN.rotated(randf_range(-PI/3, PI/3))
	screen_size = get_viewport_rect().size

func _process(delta: float) -> void:
	if direction.length() > 0:
		position += speed * delta * direction
	if position.y > screen_size.y:
		stop()

func _on_body_entered(body: Node2D) -> void:
	# 如果碰撞的是墙壁
	if body.is_in_group("walls"):
		# 如果是左右墙壁，那么将 x 方向翻转；如果是上部墙壁将 y 方向翻转
		if abs(position.x - body.position.x) < abs(position.y - body.position.y):
			direction.x *= -1
		else:
			direction.y *= -1

@warning_ignore("unused_parameter")
func _on_area_entered(area: Area2D) -> void:
	# 如果碰撞的是挡板，y 方向翻转
	direction.y *= -1
	hit.emit()

func speedup() -> void:
	speed += 50
	print("ball speedup to ", speed)
	
func slowdown() -> void:
	speed -= 50
	if speed < 50:
		speed = 50
	print("ball slowdown to ", speed)

func start(pos):
	position = pos
	show()
	$CollisionShape2D.disabled = false

func stop():
	hide()
	leaved.emit()
	queue_free()
